package org.tigris.atlas.beehive;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.beehive.netui.pageflow.PageFlowRequestProcessor;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.config.ForwardConfig;
import org.tigris.atlas.messages.MessageFactory;
import org.tigris.atlas.messages.Messages;
import org.tigris.atlas.messages.MessagesHandler;
import org.tigris.atlas.web.struts.InputForm;

public class RequestProcessor extends PageFlowRequestProcessor {

	protected boolean processValidate(HttpServletRequest request,
			                          HttpServletResponse response,
			                          ActionForm form,
			                          ActionMapping mapping) throws IOException, ServletException {

		if(form == null) {
			return true;
		}

		// Was this request cancelled?
		if(request.getAttribute(Globals.CANCEL_KEY) != null) {
			return true;
		}
		
		// Has validation been turned off for this mapping?
		if(!mapping.getValidate()) {
			return true;
		}

		// Call InputForm's validate method to find any errors
		InputForm inputForm;
		try {
			inputForm = (InputForm) form;
			inputForm.validate(request);
		} catch (ClassCastException ex) {
			throw new IllegalArgumentException("RequestProcessor can only process subclasses of InputForm");
		}
		
		// Ensure that errors are copied to the form
		// Somewhat redundant, but ensures field-level messages are set
		Messages messages = inputForm.getMessages();
		inputForm.addMessages(inputForm.getMessages(), request);
		
		// Handle any messages
		MessagesHandler handler = MessageFactory.createMessagesHandler();
		handler.handleMessages(messages, form.getClass(), request);
		
		if (!messages.hasErrorMessages()) {
			return true;
		}

		// Special handling for multipart request
		if(form.getMultipartRequestHandler() != null) {
			form.getMultipartRequestHandler().rollback();
		}

		// Has an input form been specified for this mapping?
		String input = mapping.getInput();
		if(input == null) {
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
					           getInternal().getMessage("noInput", mapping.getPath()));
			return false;
		}

		if(moduleConfig.getControllerConfig().getInputForward()) {
			ForwardConfig forward = mapping.findForward(input);
			processForwardConfig(request, response, forward);
		} else {
			internalModuleRelativeForward(input, request, response);
		}
		
		return false;
	}
	
}
